package com.supreme.nettyapp.generalserver.controller;

import com.supreme.nettyapp.generalserver.mqttserver.model.SessionStore;
import com.supreme.nettyapp.generalserver.utils.ChannelStoreUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@RequestMapping(value = "netty")
public class NettyController {

    @GetMapping(value = "hello")
    public String hello() {
        return "hello";
    }

    @GetMapping(value = "sendMessage/{clientId}/{topic}")
    public String sendMessage(@PathVariable(value = "clientId") String clientId,
                              @PathVariable(value = "topic") String topic) {
        SessionStore sessionStore = ChannelStoreUtils.getSessionStore(clientId);
        Optional<Channel> channelOptional = Optional.ofNullable(sessionStore).map(SessionStore::getChannel);
        if (!channelOptional.isPresent()) {
            return "error";
        }

        ByteBuf byteBuf = Unpooled.wrappedBuffer("message".getBytes());
        MqttPublishMessage mqttPublishMessage = (MqttPublishMessage) MqttMessageFactory.newMessage(
                new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.AT_MOST_ONCE, false, 0),
                new MqttPublishVariableHeader(topic, 0), Unpooled.wrappedBuffer(byteBuf)
        );

        Channel channel = channelOptional.get();
        channel.writeAndFlush(mqttPublishMessage);
        return "success";
    }
}
